# -*- coding: utf-8 -*-

import os
import ConfigParser
from log.logger import logger


class Config(ConfigParser.ConfigParser):
    def __init__(self, config_file):
        ConfigParser.ConfigParser.__init__(self)
        self.config_file = config_file
        # do not make the upper case to lower
        self.optionxform = str
        self.read(config_file)
        # logger.info('Read the conf file [{0}] successfully.'.format(config_file))

    def getstring(self, section, option, default_value=None):
        try:
            value = self.get(section, option)
            if isinstance(value, str) and value.startswith(('\'', '\"')) and value.endswith(('\'', '\"')):
                # if the value == "''", the new value == ''
                new_value = value[1:-1]
            else:
                new_value = value
            return new_value
        except ConfigParser.NoOptionError as e:
            if default_value is not None:
                return default_value
            raise e
        except Exception as e:
            raise e

    def setstring(self, section, option, value):
        if isinstance(value, str) and value.startswith(('\'', '\"')) and value.endswith(('\'', '\"')):
            new_value = value[1:-1]
        else:
            new_value = value
        self.set(section=section, option=option, value=new_value)

    def setint(self, section, option, value):
        self.set(section, option, value)


def conf_load(cfile, save_section=True):
    try:
        conf = Config(cfile)
    except Exception as e:
        logger.error("Parser the conf file [{0}] failed, Message: [{1}].".format(cfile, e))
        return None

    if save_section:
        obj = {}
        for section in conf.sections():
            section_obj = {}
            # the function items() is different from items() of dict
            for option, value in conf.items(section):
                if isinstance(value, str) and value.startswith(('\'', '\"')) and value.endswith(('\'', '\"')):
                    # if the value == "''", the new value == ''
                    value = value[1:-1]
                else:
                    value = value

                section_obj[option] = value

            obj[section] = section_obj
    else:
        obj = {}
        for section in conf.sections():
            # the function items() is different from items() of dict
            for option, value in conf.items(section):
                if isinstance(value, str) and value.startswith(('\'', '\"')) and value.endswith(('\'', '\"')):
                    # if the value == "''", the new value == ''
                    value = value[1:-1]
                else:
                    value = value

                obj[option] = value

    return obj


def conf_dump(obj, cfile):
    has_section = True
    for _, value in obj.items():
        if not isinstance(value, dict):
            has_section = False
            break

    if has_section:
        # create and empty the conf file
        os.system('> {0}'.format(cfile))
        for section, values in obj.items():
            os.system('echo [{0}] >> {1}'.format(section, cfile))
    else:
        os.system('echo [default] > {0}'.format(cfile))
    conf = Config(cfile)

    if has_section:
        for section, values in obj.items():
            for option, value in values.items():
                if isinstance(value, str) and value.startswith(('\'', '\"')) and value.endswith(('\'', '\"')):
                    value = "'{0}'".format(value[1:-1])
                else:
                    value = "'{0}'".format(value)

                conf.set(section=section, option=option, value=value)
    else:
        for option, value in obj.items():
            if isinstance(value, str) and value.startswith(('\'', '\"')) and value.endswith(('\'', '\"')):
                value = "'{0}'".format(value[1:-1])
            else:
                value = "'{0}'".format(value)

            conf.set(section='default', option=option, value=value)

    conf.write(open(cfile, "w"))

